package com.example.calendar.ui.screens.task

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.calendar.data.model.Task
import com.example.calendar.data.model.TaskPriority
import com.example.calendar.data.repository.CategoryRepository
import com.example.calendar.data.repository.TaskRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.threeten.bp.LocalDate
import org.threeten.bp.LocalDateTime
import org.threeten.bp.LocalTime
import java.util.UUID
import javax.inject.Inject

/**
 * ViewModel for creating and editing tasks
 */
@HiltViewModel
class TaskViewModel @Inject constructor(
    private val taskRepository: TaskRepository,
    private val categoryRepository: CategoryRepository,
    private val savedStateHandle: SavedStateHandle
) : ViewModel() {
    
    // The ID of the task being edited, or null if creating a new task
    private val taskId: String? = savedStateHandle.get<String>("taskId")
    
    // State for the UI
    private val _uiState = MutableStateFlow(TaskUiState())
    val uiState: StateFlow<TaskUiState> = _uiState.asStateFlow()
    
    init {
        // If we have a taskId, load the task details
        taskId?.let { id ->
            loadTask(id)
        }
    }
    
    /**
     * Load task details from the repository
     */
    private fun loadTask(id: String) {
        viewModelScope.launch {
            taskRepository.getTaskById(id).collect { task ->
                task?.let {
                    _uiState.update { currentState ->
                        currentState.copy(
                            id = it.id,
                            title = it.title,
                            description = it.description ?: "",
                            dueDate = it.dueDate?.toLocalDate() ?: LocalDate.now(),
                            dueTime = it.dueDate?.toLocalTime() ?: LocalTime.now(),
                            hasDueTime = it.dueDate != null,
                            isCompleted = it.isCompleted,
                            completedDate = it.completedDate,
                            priority = it.priority,
                            reminderMinutes = it.reminderMinutes,
                            categoryId = it.categoryId,
                            color = it.color,
                            isLoading = false,
                            isEditing = true
                        )
                    }
                }
            }
        }
    }
    
    /**
     * Create a new task with the current UI state
     */
    fun createTask() {
        val state = uiState.value
        
        if (state.title.isBlank()) {
            _uiState.update { it.copy(error = "Title cannot be empty") }
            return
        }
        
        val dueDateTime = if (state.hasDueTime) {
            LocalDateTime.of(state.dueDate, state.dueTime)
        } else {
            null
        }
        
        val task = Task(
            id = state.id ?: UUID.randomUUID().toString(),
            title = state.title,
            description = state.description.takeIf { it.isNotBlank() },
            dueDate = dueDateTime,
            isCompleted = state.isCompleted,
            completedDate = state.completedDate,
            priority = state.priority,
            reminderMinutes = state.reminderMinutes,
            categoryId = state.categoryId,
            color = state.color
        )
        
        viewModelScope.launch {
            if (state.isEditing) {
                taskRepository.updateTask(task)
            } else {
                taskRepository.addTask(task)
            }
        }
    }
    
    /**
     * Toggle task completion status
     */
    fun toggleTaskCompleted() {
        _uiState.update { currentState ->
            val isCompleted = !currentState.isCompleted
            val completedDate = if (isCompleted) LocalDateTime.now() else null
            currentState.copy(
                isCompleted = isCompleted,
                completedDate = completedDate
            )
        }
    }
    
    // UI State Update Functions
    
    fun updateTitle(title: String) {
        _uiState.update { it.copy(title = title) }
    }
    
    fun updateDescription(description: String) {
        _uiState.update { it.copy(description = description) }
    }
    
    fun updateDueDate(date: LocalDate) {
        _uiState.update { it.copy(dueDate = date) }
    }
    
    fun updateDueTime(time: LocalTime) {
        _uiState.update { it.copy(dueTime = time) }
    }
    
    fun updateHasDueTime(hasDueTime: Boolean) {
        _uiState.update { it.copy(hasDueTime = hasDueTime) }
    }
    
    fun updatePriority(priority: TaskPriority) {
        _uiState.update { it.copy(priority = priority) }
    }
    
    fun updateReminder(reminderMinutes: Int) {
        if (reminderMinutes > 0) {
            _uiState.update { it.copy(reminderMinutes = listOf(reminderMinutes)) }
        }
    }
    
    fun clearError() {
        _uiState.update { it.copy(error = null) }
    }
}

/**
 * UI state for the task screen
 */
data class TaskUiState(
    val id: String? = null,
    val title: String = "",
    val description: String = "",
    val dueDate: LocalDate = LocalDate.now(),
    val dueTime: LocalTime = LocalTime.now(),
    val hasDueTime: Boolean = true,
    val isCompleted: Boolean = false,
    val completedDate: LocalDateTime? = null,
    val priority: TaskPriority = TaskPriority.MEDIUM,
    val reminderMinutes: List<Int> = emptyList(),
    val categoryId: String? = null,
    val color: Int? = null,
    val isLoading: Boolean = false,
    val isEditing: Boolean = false,
    val error: String? = null
) 